#include <QEvent>
#include <QTimer>

#include <lgpl-components/cobjectmanager.h>
#include <messaginglayer/iprofile.h>

#include "startupwidget.h"
#include "ui_startupwidget.h"

StartupWidget::StartupWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::StartupForm)
{
    m_state = Idle;

    ui->setupUi(this);
    ui->progressIndicator->setAnimationDelay(80);
    ui->progressIndicator->setVisible(false);
    //updateKeyboardLayoutIndicator();

    connect(ui->logIn, SIGNAL(released()), this, SLOT(logInOrAbort()));
}

StartupWidget::~StartupWidget()
{
    delete ui;
}

void StartupWidget::connected()
{
    changeState(Idle);
    setProgressMessage(QString());
}

void StartupWidget::connectionError(const QString &errorString)
{
    changeState(Idle);
    setProgressMessage(errorString, true);
}

void StartupWidget::connectProfile()
{
    setProgressMessage(tr("Please wait..."));

    CAuthInfo authInfo;
    QStringList auth;

    auth = ui->user->currentText().split("@");
    if (auth.count() != 2) {
        setProgressMessage(tr("Enter correct user"), true);
        return;
    }
    authInfo.setHost(auth.at(1));
    QList<IProfile *> iprofiles = CObjectManager::instance()->components<IProfile>();
    foreach (IProfile * iprofile, iprofiles) {
        if (iprofile->match(authInfo))
            iprofile->fillAuthInfo(&authInfo);
    }

    authInfo.setUser(auth.at(0));
    authInfo.setPassword(ui->password->text());
    emit connectionRequest(authInfo);
}

void StartupWidget::abortConnecting()
{
    setProgressMessage(tr("Connecting canceled"), true);
}

bool StartupWidget::event(QEvent *e)
{
//    if (e->type() == QEvent::KeyboardLayoutChange)
//        updateKeyboardLayoutIndicator();
    if (e->type() == QEvent::LanguageChange)
        ui->retranslateUi(this);
    return QWidget::event(e);
}

void StartupWidget::updateKeyboardLayoutIndicator()
{
    QString language;

    language = QLocale::languageToString(QApplication::keyboardInputLocale().language());
    ui->password->setPlaceholderText(tr("Keyboard Layout: %1").arg(language));
}

void StartupWidget::setProgressMessage(const QString &text, bool isError)
{
    if (!text.isEmpty()) {
        if (isError) {
            ui->progressIndicator->stopAnimation();
            ui->progressIndicator->setVisible(false);
            ui->progressText->setText(QString("<span style=\"color:red\">%1</span>").arg(text));
            QTimer::singleShot(1000, this, SLOT(clearErrorText()));
        }
        else {
            if (!ui->progressIndicator->isAnimated()) {
                ui->progressIndicator->startAnimation();
                ui->progressIndicator->setVisible(true);
            }
            ui->progressText->setText(text);
        }
    } else {
        ui->progressIndicator->stopAnimation();
        ui->progressIndicator->setVisible(false);
        ui->progressText->clear();
    }
}

void StartupWidget::clearErrorText()
{
    // clear text only when no animation is.
    if (!ui->progressIndicator->isAnimated())
        ui->progressText->clear();
}

void StartupWidget::logInOrAbort()
{
    if (m_state == Idle) {
        if (ui->user->currentText().isEmpty())
            setProgressMessage(tr("Valid user required"), true);
        else {
            changeState(Connecting);
            connectProfile();
        }
    } else {
        changeState(Idle);
        abortConnecting();
    }
}

void StartupWidget::changeState(State state)
{
    if (state == Connecting) {
        ui->logIn->setText(tr("Cancel"));
        ui->logIn->setDisabled(true);
    } else {
        ui->logIn->setText(tr("Log In"));
        ui->logIn->setEnabled(true);
    }
    m_state = state;
}
